package qe.spider.tools;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.UnicodeUtil;
import com.google.gson.*;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import qe.spider.grab.ParseThsStock;
import qe.spider.trade.SendBuySignal;
import qe.spider.trade.SendSellSignal;
import qe.spider.trade.TradeAnalyser;
import qe.spider.vo.GoodStock;
import qe.spider.vo.Stock;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Slf4j
public class WSNotice {
    private final String webHook = "http://" + System.getProperty("wsn_ip", "47.99.196.159") + ":" + System.getProperty("wsn_port", "8888") + "/gs/gstocks/";
    //        private final String webHook = "http://127.0.0.1:8888/gs/gstocks/";
    List<GoodStock> goodStocks;
    Boolean isNew;

    public WSNotice(List<GoodStock> goodStocks, Boolean isNew) {
        this.goodStocks = goodStocks;
        this.isNew = isNew;
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        List<GoodStock> gs = new WSNotice(new ArrayList<>(), false).recovery();
        GoodStock goodStock = gs.get(0);
        SendBuySignal.buy(goodStock, new Stock().code(goodStock.getCode()).name(goodStock.getName()));
        ParseThsStock parser = new ParseThsStock(new File("D:\\Tools\\THSGeGuData\\" + "2024-04-06\\180608.xls"));
        parser.parseTitle();
        parser.parseAllLines();
        SendSellSignal.sell("real_trade_fall_avg", gs.get(0), parser.getAll().stream().filter(s -> s.getStock_code().equals(gs.get(0).getCode())).findFirst().get());
        new TradeAnalyser(parser.getAll()).genSellRecord(gs.get(0), parser.getAll().stream().filter(s -> s.getStock_code().equals(gs.get(0).getCode())).findFirst().get(), "test");
        List<GoodStock> goodStocks = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            new WSNotice(goodStocks, true).replay("2024-02-26");
            Thread.sleep(1000L);
        }
//        new WSNotice(new ArrayList<>(), false).send();
    }

    public String buildJson() {
        Map<String, Object> msg = Map.of("stocks", goodStocks, "count", goodStocks.size(), "isNew", this.isNew);
        String json = new GsonBuilder().setPrettyPrinting().create().toJson(msg);
        log.info("wsNotice----\n{}", json);
        return json;
    }

    public RequestBody formBody() {
        String json = buildJson();
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), json);
        if (!goodStocks.isEmpty())
            FileUtil.writeString(json, new File(System.getProperty("save_path", System.getProperty("user.dir", "..")) + "/tops/" + DateUtil.today() + ".json"), "UTF-8");
        return body;
    }

    public Boolean send() {
        OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder().url(webHook).header("Content-Type", "application/json").post(formBody()).build();
        log.debug(request.body().toString());
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) return false;
            String result = UnicodeUtil.toString(response.body().string());
            log.debug(result);
            return true;
        } catch (IOException e) {
            log.error("WebSocket msg send error： ", e);
        }
        return true;
    }

    public Boolean replay(String filename) {
        String json = FileUtil.readString(new File(System.getProperty("save_path", System.getProperty("user.dir", "..")) + "/tops/" + filename + ".json"), "UTF-8");
        OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder().url(webHook).header("Content-Type", "application/json").post(RequestBody.create(MediaType.parse("application/json;charset=utf-8"), json)).build();
        log.debug(request.body().toString());
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) return false;
            String result = UnicodeUtil.toString(response.body().string());
            log.debug(result);
            return true;
        } catch (IOException e) {
            log.error("WebSocket msg send error： ", e);
        }
        return true;
    }

    public List<GoodStock> recovery() {
        File file = new File(System.getProperty("save_path", System.getProperty("user.dir", "..")) + "/tops/" + DateUtil.today() + ".json");
        Boolean topToday = FileUtil.exist(new File(System.getProperty("save_path", System.getProperty("user.dir", "..")) + "/tops/" + DateUtil.today() + ".json"));
        log.info("恢复上榜股票----{}----路径：{}", topToday, file.getAbsolutePath());
        if (!topToday) return new ArrayList<>();
        String json = FileUtil.readString(new File(System.getProperty("save_path", System.getProperty("user.dir", "..")) + "/tops/" + DateUtil.today() + ".json"), "UTF-8");
        JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();
        jsonObject.getAsJsonObject();
        JsonArray stocks = jsonObject.getAsJsonArray("stocks");
        return IntStream.range(0, stocks.size()).mapToObj(i -> new Gson().fromJson(stocks.get(i).getAsJsonObject(), GoodStock.class)).collect(Collectors.toList());

    }
}
